import type { LogSchema, RiskReportSchema } from "@/types/account.types";
import { computed, h } from "vue";
import dayjs from "@/utils/dayjs";
import { formatRiskArguments } from "@/utils/riskFormatting";

export const useTradeLogsTable = () => {
  const tableSize = computed<"" | "small" | "default" | "large">(() => "small");

  const getRowClassName = (row: LogSchema) => {
    const level = Number(row.level ?? 0);
    // Map common log levels to colors (Element Plus row class names via utility classes)
    if (level >= 40) return " text-red-700"; // error
    if (level >= 30) return " text-orange-700"; // warn
    if (level >= 20) return "text-gray-600"; // debug
    return "text-gray-500"; // trace/verbose
  };

  const columns: TableColumnList = [
    {
      label: "时间",
      prop: "time",
      minWidth: 70,
      sortable: true,
      sortMethod: (a: LogSchema, b: LogSchema) =>
        dayjs(a.time).valueOf() - dayjs(b.time).valueOf(),
      formatter: (row: LogSchema) => {
        const t = row?.time ? dayjs(row.time) : null;
        return t && t.isValid() ? t.format("HH:mm:ss") : "-";
      }
    },
    {
      label: "来源",
      prop: "source",
      minWidth: 70,
      showOverflowTooltip: true,
      formatter: (row: LogSchema) => row.source ?? ""
    },
    {
      label: "消息",
      prop: "msg",
      minWidth: 200,
      showOverflowTooltip: true,
      formatter: (row: LogSchema) => row.msg ?? ""
    }
  ];

  const logColumns = computed(() => columns);

  return { tableSize, logColumns, getRowClassName };
};

export const useRiskReportsTable = () => {
  const tableSize = computed<"" | "small" | "default" | "large">(() => "small");

  const columns: TableColumnList = [
    {
      label: "规则名称",
      prop: "name",
      minWidth: 80,
      showOverflowTooltip: true
    },
    {
      label: "模板名称",
      prop: "template",
      minWidth: 100,
      showOverflowTooltip: true
    },
    {
      label: "参数",
      prop: "arguments",
      minWidth: 150,
      showOverflowTooltip: true,
      cellRenderer: ({ row }) =>
        h(
          "pre",
          {
            class:
              "m-0 w-full whitespace-pre-wrap break-words font-mono text-[10px] text-text_color_primary"
          },
          formatRiskArguments((row as RiskReportSchema | undefined)?.arguments)
        )
    },
    {
      label: "状态报告",
      prop: "report",
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      label: "时间",
      prop: "time",
      minWidth: 100,
      showOverflowTooltip: true,
      formatter: (row: RiskReportSchema) =>
        row.time ? dayjs(row.time).format("YYYY-MM-DD HH:mm:ss") : "-"
    }
  ];

  const riskReportColumns = computed(() => columns);

  return { tableSize, riskReportColumns };
};
